package ee.ut.aa.neuraltic.model;

import java.util.ArrayList;

import org.apache.log4j.Logger;

public class TicBoard implements Board {

	private static Logger log = Logger.getLogger( TicBoard.class );

	private int[] fields = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	private int size = 9;

	private int nextPlayer = PLAYER_ONE;

	public TicBoard() {
	}

	public TicBoard( int[] fields, int nextPlayer ) {

		this.fields = fields;
		this.size = fields.length;
		this.nextPlayer = nextPlayer;
	}

	@Override
	public int getSize() {

		return size;
	}

	@Override
	public int getValue( int index ) {

		int value = fields[index];

		log.debug( "Returning value " + value + " at index \t" + index );

		return value;
	}

	@Override
	public void setValue( int index, int value ) {

		log.debug( "Setting value " + value + " at index \t" + index );

		fields[index] = value;
	}

	@Override
	public void makeMove( int index ) {

		setValue( index, nextPlayer );

		// Switch nextPlayer;
		nextPlayer = nextPlayer == PLAYER_ONE ? PLAYER_TWO : PLAYER_ONE;
	}

	@Override
	public int[] getFields() {
		log.debug( "Returning board fields." );

		return fields;
	}

	@Override
	public void setFields( int[] fields ) {

		this.fields = fields;
	}

	@Override
	public int getNextPlayer() {
		return nextPlayer;
	}

	@Override
	public void setNextPlayer( int nextPlayer ) {
		this.nextPlayer = nextPlayer;
	}

	@Override
	public boolean isLegalMove( int index ) {

		boolean result = fields[index] == 0;

		log.debug( "Checking legal move for index " + index + ", result = " + result );

		return result;
	}

	@Override
	public ArrayList<Integer> getLegalMoves() {

		ArrayList<Integer> result = new ArrayList<Integer>();

		for( int i = 0; i < fields.length; i++ ) {

			if( fields[i] == 0 )
				result.add( i );
		}

		log.debug( "Returning legal moves: " + result );

		return result;
	}

	@Override
	public String toString() {

		String result = "\n";

		result += "" + fields[0] + "|" + fields[1] + "|" + fields[2] + "\n";
		result += "-----------\n";
		result += "" + fields[3] + "|" + fields[4] + "|" + fields[5] + "\n";
		result += "-----------\n";
		result += "" + fields[6] + "|" + fields[7] + "|" + fields[8];
		
		result = result.replaceAll( "0", "   " );
		result = result.replaceAll( "-1", " o " );
		result = result.replaceAll( "1", " x " );

		return result;
	}
}
